package com.cmii.sjw.department.control.jsc.service.impl;

import com.cmii.sjw.department.control.jsc.service.AizhxyService;
import com.cmii.sjw.department.control.jsc.vo.CanteenInfoVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Slf4j
@Service
public class AizhxyServiceImpl implements AizhxyService {


    private static final String BASE_URL = "http://10.48.34.56:8080/tempSchool/api";
    private static final String TOKEN = "d2a7e9a510178c5321e9ab0d1c7d6c7d";

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public CanteenInfoVO getCanteenInfo() {
        CanteenInfoVO vo = new CanteenInfoVO();
        try {
            // 通用 Header
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + TOKEN);
            HttpEntity<String> entity = new HttpEntity<>(headers);

            // 1. 食材品目数量
            ResponseEntity<String> foodResp = restTemplate.exchange(
                    BASE_URL + "/getFoodCategoryNum", HttpMethod.GET, entity, String.class);
            JsonNode foodJson = objectMapper.readTree(foodResp.getBody());
            vo.setFoodCategoryNum(foodJson.path("data").get(0).path("totalNum").asInt());

            // 2. 验收合格率
            ResponseEntity<String> qualifiedResp = restTemplate.exchange(
                    BASE_URL + "/getQualifiedRate", HttpMethod.GET, entity, String.class);
            JsonNode qualifiedJson = objectMapper.readTree(qualifiedResp.getBody());
            vo.setQualifiedRate(qualifiedJson.path("data").get(0).path("qualifiedRate").asDouble());

            // 3. 风险问题数量
            ResponseEntity<String> riskResp = restTemplate.exchange(
                    BASE_URL + "/getRiskNum", HttpMethod.GET, entity, String.class);
            JsonNode riskJson = objectMapper.readTree(riskResp.getBody());
            vo.setRiskNum(riskJson.path("data").get(0).path("riskNum").asInt());

            // 4. 上月整体满意度
            ResponseEntity<String> satisfactionResp = restTemplate.exchange(
                    BASE_URL + "/getLastMonthSatisfaction", HttpMethod.GET, entity, String.class);
            JsonNode satisfactionJson = objectMapper.readTree(satisfactionResp.getBody());
            vo.setSatisfaction(satisfactionJson.path("data").get(0).path("satisfaction").asDouble());

        } catch (Exception e) {
            log.error("获取信息失败：{}", e.getMessage(), e);
        }
        return vo;
    }
}

